package com.question.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.itcast.servlet.BaseServlet;

import com.question.domain.Academy;
import com.question.domain.Student;
import com.question.domain.Topic;
import com.question.service.AcademyService;
import com.question.service.StudentService;
import com.question.service.TopicService;
import com.question.service.serviceFactory.ServiceFactory;
import com.question.utils.IntegerTools;
import com.question.utils.MyProperties;
import com.question.utils.StringTools;

/**
 * Servlet implementation class questionServlet
 */
public class QuestionServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private StudentService studentService = ServiceFactory.getInstance().getStudentService();
	private TopicService topicService = ServiceFactory.getInstance().geTopicService();
	private AcademyService academyService = ServiceFactory.getInstance().getAcademyService();

	private MyProperties properties = new MyProperties();
	/*
	 * 登录
	 */
	public String login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		Student stu = new Student();
		
		String userName = req.getParameter("userName");
		String academy = req.getParameter("academy");
		String userId = req.getParameter("userId");
		stu.setStudentId(Integer.valueOf(userId));
		stu.setAcademy(academy);
		stu.setUserName(userName);
		
		System.out.println(stu.toString());
		//检查对象
		if((studentService.findUserById(stu))!=null){
			stu = studentService.findUserById(stu);
			return "r:/grade.jsp?id="+stu.getStudentId();
		}
		studentService.insertStu(stu);
		//重定向返回参数到answer.jsp
		//这行没有参数
		String in = "r:/answer.jsp?topic="+IntegerTools.intArrToString(topicService.getTopicNumber())
				+"&id="+stu.getStudentId();
		return in;
	}

	/*
	 * 传出题目
	 */
	public void giveTopic(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String nowIndex = req.getParameter("index");
		String studentId = req.getParameter("studentId");
		//检查是否有成绩
		Student stu = new Student();
		stu.setStudentId(Integer.parseInt(studentId));
		stu = studentService.findUserById(stu);
		if(stu.getTime()!=0){
			JSONObject obj  =JSONObject.fromObject(stu);
			resp.getWriter().print(obj.toString());
			return;
		}
		
		Topic topic = getLastTopic(Integer.parseInt(nowIndex));
		//我在js代码里会先设置好最大的题目数  但是为了便于以后修改 还是做好准备
		if(topic==null){
			resp.getWriter().print(-1);
			throw new RuntimeException();
		}
		//将题目对象转换成json字符串   
		JSONObject obj  =JSONObject.fromObject(topic);
		System.out.println(topic.toJSPString());
		//将json对象返回给页面
		resp.getWriter().print(obj.toString());
	}

	//产生下一题
	/*
	*   传入页面上的最大题题号
		传出一个返回给界面的题目
	*/
	public Topic getLastTopic(int index){
		try {
			Topic topic = topicService.getTopicByIndex(index+1);
			return topic;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	//获取院系排名的一个方法  你自己剪切移动位置
	public void getAcademyRank(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//假定所有的院系都存在一个ArrayList里
		ArrayList<Academy> list = (ArrayList<Academy>)academyService.getAcademyRank();
		JSONArray array  = new JSONArray();
		for(Academy academy:list){
			JSONObject object = JSONObject.fromObject(academy);
			array.add(object);
		}
		resp.getWriter().print(array.toString());
	}
	
	/*
	 * 统计分数
	 */
	public void calculateScores(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//这里获取到ajax提供的答案，以及学生信息和时间
		System.out.println("dgagkd");
		Student stu = new Student();
		String answer =req.getParameter("answer");
		String score = req.getParameter("score");
		String time = req.getParameter("time");
		
		if(answer.replaceAll(" ", "").equals("")){
			return;
		}
		//根据学号获取到学生的信息  假设学生为stu  你自己获取
		stu.setStudentId(Integer.valueOf(score));
		stu = studentService.findUserById(stu);
		stu.setTime(Integer.valueOf(time));
		//分割答案 假定最大题目数为Max
		//答案格式：1A2B3C4D....10ABCD...
		int Max = Integer.valueOf(properties.getProperties("totalTopic"));
		//预计的答案格式为：A||B||C....||ABCD...
		Map<Integer, String> map_topicSelf = StringTools.splitAnswer(answer);
		//计算答案的正确性  得出分数 计算排名
		int grade = topicService.getGrade(map_topicSelf);
		stu.setScoure(grade);
		//更新学生数据
		studentService.update(stu);
		//更新学院数据
		academyService.reRank(stu);
		
		stu = studentService.findUserById(stu);
		stu.setRank(studentService.getRank(stu));
		JSONObject object  = JSONObject.fromObject(stu);
		
		System.out.println(object.toString());
		resp.getWriter().print(object.get("studentId"));
	}

	/*
	 * 传出排名
	 */
	public void giveRank(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
			
			//内含学生前n个排名，n由配置文件提供
			ArrayList<Student> arr = (ArrayList<Student>) studentService.getRanks();
			JSONArray array = new JSONArray();
			//增加全部学生的信息
			for(Student s:arr){
				JSONObject object = JSONObject.fromObject(s);
				System.out.println(object.toString());
				array.add(object);
			}
			
			//增加个人信息
			String studentId = req.getParameter("studentId");
			Student stu =new Student();
			stu.setStudentId(Integer.parseInt(studentId));
			stu = studentService.findUserById(stu);
			array.add(JSONObject.fromObject(stu));
			//输出信息
			resp.getWriter().print(array.toString());
	}

}
